package com.sharding.issuse.conf;

import com.alibaba.druid.pool.DruidDataSource;
import io.shardingjdbc.core.api.ShardingDataSourceFactory;
import io.shardingjdbc.core.api.config.ShardingRuleConfiguration;
import io.shardingjdbc.core.api.config.TableRuleConfiguration;
import io.shardingjdbc.core.api.config.strategy.InlineShardingStrategyConfiguration;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
@EnableTransactionManagement
public class SpringDatasourceConfig implements EnvironmentAware {

    @Autowired
    MybatisProperties properties;

    private RelaxedPropertyResolver propertyResolver;

    @Override
    public void setEnvironment(Environment env) {
        this.propertyResolver = new RelaxedPropertyResolver(env, "spring.datasource.");
    }

    @Bean
    public DataSource dataSource() {


        Map<String, DataSource> dataSourceMap = new HashMap<>();

        dataSourceMap.put("messagerobot", createDataSource());

        TableRuleConfiguration autoRuleFlowTaskTableRuleConfig = new TableRuleConfiguration();
        autoRuleFlowTaskTableRuleConfig.setLogicTable("robot_contact");
        autoRuleFlowTaskTableRuleConfig.setKeyGeneratorColumnName("id");
        autoRuleFlowTaskTableRuleConfig.setTableShardingStrategyConfig(new InlineShardingStrategyConfiguration("case_id", "robot_contact_${case_id % 7}"));

        // 配置分片规则
        ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
        shardingRuleConfig.getTableRuleConfigs().addAll(Arrays.asList(autoRuleFlowTaskTableRuleConfig));
        shardingRuleConfig.setDefaultKeyGeneratorClass("io.shardingjdbc.core.keygen.DefaultKeyGenerator");

        try {
            Properties props = new Properties();
            props.put("sql.show", "true");

            return ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfig, new ConcurrentHashMap(), props);


        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public DataSource createDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(propertyResolver.getProperty("url"));
        dataSource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
        dataSource.setUsername(propertyResolver.getProperty("username"));
        dataSource.setPassword(propertyResolver.getProperty("password"));
        return dataSource;
    }


    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactoryBean sqlSessionFactory() {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource());
        bean.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
        bean.setConfigLocation(new DefaultResourceLoader().getResource("classpath:mybatisConfig.xml"));
        bean.setMapperLocations(this.properties.resolveMapperLocations());
        return bean;

    }

    @Bean(name = "spacexTransactionManager")
    public DataSourceTransactionManager spacexTransactionManager() throws SQLException {
        return new DataSourceTransactionManager(dataSource());
    }


    //@Bean
    //public DataSource createDataSource() {
    //    DruidDataSource dataSource = new DruidDataSource();
    //    dataSource.setUrl(propertyResolver.getProperty("url"));
    //    dataSource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
    //    dataSource.setUsername(propertyResolver.getProperty("username"));
    //    dataSource.setPassword(propertyResolver.getProperty("password"));
    //    return dataSource;
    //}
    //
    //@Bean(name = "sqlSessionFactory")
    //public SqlSessionFactoryBean sqlSessionFactory() {
    //    SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    //    bean.setDataSource(createDataSource());
    //    bean.setTypeAliasesPackage(this.properties.getTypeAliasesPackage());
    //    bean.setConfigLocation(new DefaultResourceLoader().getResource("classpath:mybatisConfig.xml"));
    //    bean.setMapperLocations(this.properties.resolveMapperLocations());
    //    return bean;
    //
    //}
    //
    //@Bean(name = "spacexTransactionManager")
    //public DataSourceTransactionManager spacexTransactionManager() throws SQLException {
    //    return new DataSourceTransactionManager(createDataSource());
    //}
}
